from django.shortcuts import render, redirect
from ManageApp.models import *
from ManageApp.utils.page_nav import PageNav
from ManageApp.utils.bootstrap import BootstrapForm
from django import forms


class UserModelForm(BootstrapForm):
    age = forms.IntegerField(required=True,
                             widget=forms.TextInput(attrs={'class': 'form-control',"type": "number",
                                                           "placeholder": "年龄", "min": "0", "max": "200"}))
    create_time = forms.DateTimeField(required=False,widget=forms.TextInput(attrs={'class': 'form-control',"type": "datetime-local"}))

    class Meta:
        model = UserInfo
        fields = ["user_id", "name", "password", "account", "age", "create_time", "gender", "department"]
def user_list(req):
    search_data_dict = {}
    search_data = req.GET.get("q", "")

    if search_data:
        search_data_dict["name__contains"] = search_data
        # mobile__contains==xx 作为filter参数表示字符串包含xx 类似的 还有 __gt __lte __startwith
    queryset = UserInfo.objects.filter(**search_data_dict)
    # 相当于 order by level desc ,   queryset切片可以越界但要为正数

    # queryset = UserInfo.objects.all()
    page_nav_obj = PageNav(req, queryset)
    page_queryset = page_nav_obj.page_queryset
    page_nav_string = page_nav_obj.get_html()
    content = {
        "queryset": page_queryset,
        "page_nav_string": page_nav_string,
    }
    return render(req, "user_list.html", content)

def user_add(req):
    if req.method == "GET":
        form = UserModelForm()
        return render(req, "user_add.html", {"form": form})
    form = UserModelForm(data=req.POST)  # 用post的消息更新表单，没有instance表示新增而不是修改
    if form.is_valid():
        if form.instance.create_time is not None:  #获取这个表单绑定的模型对象的 create_time 字段
            import datetime
            form.instance.create_time = datetime.datetime.now()
        form.save()
        return redirect("user/list")
    else:
        return render(req, "user_add.html", {"form": form})

def user_delete(req):
    nid = req.GET.get("nid")
    row_obj = UserInfo.object.filter(user_id=nid)
    if row_obj:
        row_obj.delete()
    return redirect("user/list")


def user_edit(req, nid):
    row_obj = UserInfo.objects.filter(user_id=nid).first()
    form = UserModelForm(instance=row_obj)
    if req.method == "GET":
        return render(req, "user_edit.html", {"form": form})
    else:
        form = UserModelForm(instance=row_obj, data=req.POST)
        if form.is_valid():
            if form.instance.create_time is not None:
                import datetime
                form.instance.create_time = datetime.datetime.now()
            form.save()
            return redirect("user/list")
    return render(req, "user_edit.html", {"form": form})

